import {
    BlockComponentTypes,
    EntityComponentTypes,
    ItemStack,
    Vector3,
    world,
} from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { Vector3Utils } from "@sapi-game/utils";
import { parkourGameModule } from "@/parkour/module";
import { PKParkourControlState } from "@/parkour/pkState/pkState";
import { PKEffectBlockComponent } from "@/parkour/effectBlocks/effectBlock";
import { PKBuildDaemonComponent } from "./components/daemon";
import { PKMapBoundaryComponent } from "./components/mapBoundary";
import { PKSkipBuildComponent } from "./components/skipBuild";

export class PKBuildState extends parkourGameModule.State {
    blueSpawnPos?: Vector3;
    redSpawnPos?: Vector3;

    override onEnter(): void {
        this.init();
        this.addComponent(Timer, {
            initialTime: this.context.config.buildTime,
            autoStart: true,
            compensate: true,
        })
            .addComponent(PKMapBoundaryComponent)
            .addComponent(PKBuildDaemonComponent)
            .addComponent(PKSkipBuildComponent);
        if (this.context.config.blockEnabled) {
            this.addComponent(PKEffectBlockComponent);
        }
        //时间结束就下一阶段
        const timer = this.getComponent(Timer);
        this.subscribe(
            timer.events.onTime,
            () => {
                this.toNextState();
            },
            { time: 0 }
        );
    }

    init() {
        this.blueSpawnPos = Vector3Utils.add(
            this.context.blue.base,
            this.context.map.spawnPos
        );
        this.redSpawnPos = Vector3Utils.add(
            this.context.red.base,
            this.context.map.spawnPos
        );
        this.context.blue.team.forEach((p) =>
            p.player?.teleport(this.blueSpawnPos!)
        );
        this.context.red.team.forEach((p) =>
            p.player?.teleport(this.redSpawnPos!)
        );
        this.context.groupSet.runCommands(["gamemode 1", "camera @s clear"]);
        this.context.groupSet.forEach((p) => {
            const container = p.player?.getComponent(
                EntityComponentTypes.Inventory
            )?.container;
            if (!container) return;
            const box = this.getBox();
            const clock = new ItemStack("minecraft:clock");
            clock.nameTag = "跳过建造阶段";
            if (box) container.addItem(box);
            container.addItem(clock);
        });
    }

    getBox() {
        const loc = Vector3Utils.above(this.context.spawn, 5);
        world.structureManager.place(
            "你的跑酷我来造:方块盒",
            Dimensions.Overworld,
            loc
        );
        return Dimensions.Overworld.getBlock(loc)
            ?.getComponent(BlockComponentTypes.Inventory)
            ?.container?.getItem(0);
    }

    toNextState() {
        this.transitionTo(PKParkourControlState);
    }
}
